package signIn;

import coupon.WebUserCoupon;
import models.BaseModel;
import models.constants.DeletedStatus;
import models.merchant.Merchant;
import models.weixin.WebUser;
import util.common.DateUtil;

import javax.persistence.*;
import java.util.Date;
import java.util.List;

/**
 * Created by liuBin on 2017/8/5.
 */
@Entity
@Table(name = "webuser_sign_in")
public class WebUserSignIn extends BaseModel {

    /**
     *  用户
     */
    @JoinColumn(name = "web_user_id")
    @ManyToOne
    public WebUser webUser;


    /**
     *  用户
     */
    @JoinColumn(name = "merchant_id")
    @ManyToOne
    public Merchant merchant;



//    /**
//     *  签到主表
//     */
//    @JoinColumn(name = "sign_in_id")
//    @ManyToOne
//    public SignIn signIn;

    /**
     * 签到次数
     */
    @Column(name = "sign_in_nums")
    public Integer signInNums;


    /**
     * 最近签到日期
     */
    @Column(name = "sign_in_date")
    @Temporal(TemporalType.TIMESTAMP)
    public Date signInDate;

    /**
     * 逻辑删除状态
     */
    @Column(name = "deleted")
    @Enumerated(EnumType.ORDINAL)
    public DeletedStatus deleted;

    public WebUserSignIn() {super();}

    public WebUserSignIn(WebUser webUser,Merchant merchant) {
        this.webUser = webUser;
        this.merchant = merchant;
        this.signInNums =  1;
        this.signInDate = new Date();
        this.deleted = DeletedStatus.UN_DELETED;
        this.createAt = new Date();
    }

    public static WebUserSignIn findByWebUserAndMerchant(WebUser webUser,Merchant merchant) {
        return WebUserSignIn.find("webUser = ? and merchant = ? and deleted = ? order by id desc" , webUser ,merchant, DeletedStatus.UN_DELETED).first();
    }

    public static List<WebUserSignIn> findListByMerchant(Merchant merchant) {
        return WebUserSignIn.find("merchant = ? and deleted = ? order by id desc",merchant,DeletedStatus.UN_DELETED).fetch();
    }

    //清空 签到中断 的 用户签到次数
    public static void updateWebUserSignIn (Merchant merchant,Integer signInDays) {
        if(merchant == null || signInDays == null || signInDays == 0) {
            return;
        }
        List<WebUserSignIn> webUserSignInList = findListByMerchant(merchant);
        for(WebUserSignIn webUserSignIn : webUserSignInList) {
            if(webUserSignIn.signInNums >= signInDays) {
                webUserSignIn.signInNums = 0;
                webUserSignIn.save();
                continue;
            }
            if(DateUtil.diffDay2(webUserSignIn.signInDate) <= -2) {
                webUserSignIn.signInNums = 0;
                webUserSignIn.save();
                continue;
            }
        }
    }

}
